package com.taiyuan.tongcheng.adapter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import net.sourceforge.simcpux.Constants;
import net.sourceforge.simcpux.MD5;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.BjOrderInfo;
import com.taiyuan.tongcheng.bean.BjOrderInfo;
import com.taiyuan.tongcheng.config.TcConfig;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.pay.WxPay;
import com.taiyuan.tongcheng.ui.MarkActivity;
import com.taiyuan.tongcheng.ui.OrderCancelActivity;
import com.taiyuan.tongcheng.util.DialogUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tytc56.user.R;
/**
 * 
* @Description 搬家adapter
* @author wzq
* @date 2015-9-22 上午10:22:39
* @update (date)
* @version V1.0
*        为1，待响应状态 （取消，定金支付）
		  为2，待收货状态 （取消，修改确定（未确定））
		  为3，待装货状态（取消，支付，修改确定（未确定））
		  为4，配送中（支付（全款）   完成 ）
		  为5，完成（评价）
* 
* 
 */

public class MovingOrderAdapter extends BaseAdapter {
	private LayoutInflater layoutInflater;
	private Context context;
	private List<BjOrderInfo> orderList=new ArrayList<BjOrderInfo>();
    private Dialog   tcLoadingDialog;
    //微信
	private PayReq req;
	public  IWXAPI msgApi;
	//跳转intent
	private Intent cancelIntent;
	private Intent markIntent;
	
	public MovingOrderAdapter(Context context, List<BjOrderInfo> orderList) {
		this.context = context;
		this.layoutInflater = LayoutInflater.from(context);
		this.orderList=orderList;
		tcLoadingDialog=new Dialog(context);
		tcLoadingDialog=DialogUtil.getTcLoadding(context);
		msgApi=WXAPIFactory.createWXAPI(context, null);
		req = new PayReq();
		msgApi.registerApp(Constants.APP_ID);
		
		cancelIntent=new Intent(context,OrderCancelActivity.class);
		markIntent=new Intent(context,MarkActivity.class);
	}
	

	public int getCount() {
		return orderList.size();
	}

	public Object getItem(int position) {
		return orderList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ZuJian zuJian = null;
		OnClick listener = null;  
		if (convertView == null) {
			zuJian = new ZuJian();
			convertView = layoutInflater.inflate(R.layout.listview_order,
					null);
			zuJian.orderKindIcon = (ImageView) convertView
					.findViewById(R.id.img_order_icon);
			zuJian.orderKind = (TextView) convertView
					.findViewById(R.id.tv_order_kind);
			zuJian.orderState = (TextView) convertView
					.findViewById(R.id.tv_order_state);
			zuJian.orderStartTime = (TextView) convertView
					.findViewById(R.id.tv_order_time);
			zuJian.orderStartPlace = (TextView) convertView
					.findViewById(R.id.tv_order_start);
			zuJian.orderEndPlace = (TextView) convertView
					.findViewById(R.id.tv_order_end);
			zuJian.orderPrice = (TextView) convertView
					.findViewById(R.id.tv_order_price);
			zuJian.orderSubBtn = (Button) convertView
					.findViewById(R.id.btn_order_kind);
			zuJian.orderMarkBtn = (Button) convertView
					.findViewById(R.id.btn_order_mark);
			zuJian.orderCancelBtn = (Button) convertView
					.findViewById(R.id.btn_order_cancel);
			zuJian.orderCakanBtn = (Button) convertView
					.findViewById(R.id.btn_order_cakan);
			zuJian.orderConfirmBtn = (Button) convertView
					.findViewById(R.id.btn_order_modify_confirm);
			zuJian.orderFinish = (Button) convertView
					.findViewById(R.id.btn_order_moving_finish);
			zuJian.orderPayPart = (Button) convertView
					.findViewById(R.id.btn_order_moving_part_pay);
			
			listener = new OnClick();// 在这里新建监听对象
			zuJian.orderSubBtn.setOnClickListener(listener);
			zuJian.orderMarkBtn.setOnClickListener(listener);
			zuJian.orderCancelBtn.setOnClickListener(listener);
			zuJian.orderCakanBtn.setOnClickListener(listener);
			zuJian.orderConfirmBtn.setOnClickListener(listener);
			zuJian.orderFinish.setOnClickListener(listener);
			zuJian.orderPayPart.setOnClickListener(listener);
			convertView.setTag(zuJian);
			convertView.setTag(zuJian.orderSubBtn.getId(), listener);// 对监听对象保存
			
		} else {
			zuJian = (ZuJian) convertView.getTag();
			listener = (OnClick) convertView.getTag(zuJian.orderSubBtn.getId());//重新获得监听对象   
		}
		BjOrderInfo orderInfo = orderList.get(position);
		zuJian.orderSubBtn.setText("全部支付");
		zuJian.orderKindIcon.setImageResource(R.drawable.icon_moving_order);
		zuJian.orderKind.setText(orderInfo.getBjOrderNo());
		refreashItemUiByStatus(zuJian.orderPrice, 
				zuJian.orderState, zuJian.orderSubBtn, 
				zuJian.orderCancelBtn, zuJian.orderMarkBtn, 
				zuJian.orderCakanBtn, zuJian.orderConfirmBtn,
				zuJian.orderPayPart,zuJian.orderFinish,orderInfo);
		
		zuJian.orderStartTime.setText(orderInfo.getServiceDate());
		zuJian.orderStartPlace.setText(orderInfo.getStartPlace());
		zuJian.orderEndPlace.setText(orderInfo.getEndPlace());
		zuJian.orderPrice.setText("总价:￥"+orderInfo.getActualOrderMoney());
		listener.setPosition(position);
		return convertView;
	}

	public final class ZuJian {
		public ImageView orderKindIcon;
		public TextView orderKind;
		public TextView orderState;
		public TextView orderStartTime;
		public TextView orderStartPlace;
		public TextView orderEndPlace;
		public TextView orderPrice;
		public Button   orderSubBtn;
		public Button   orderMarkBtn;
		public Button   orderCancelBtn;
		public Button   orderCakanBtn;
		public Button   orderConfirmBtn;
		public Button    orderPayPart;
		public Button    orderFinish;
		
	}
	
	class OnClick implements OnClickListener {
		int position;
		public void setPosition(int position) {
			this.position = position;
		}
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_order_kind:
				context.sendBroadcast(new Intent(TCBroadcastAction.DIALOG_SHOW));
				payMoney(orderList.get(position).getBjOrderId(),0);
				break;
			case R.id.btn_order_cancel:
				cancelIntent.putExtra(TcConfig.IntentTag.Order_Id, orderList.get(position).getBjOrderId());
				cancelIntent.putExtra(OrderCancelActivity.TAG_CANCEL_KIND, OrderCancelAdapter.CANCEL_ADAPTER_MOVING);
				KJLoger.debug("订单ID"+orderList.get(position).getBjOrderId());
				KJLoger.debug("订单NO"+orderList.get(position).getBjOrderNo());
				KJLoger.debug("订单状态"+orderList.get(position).getStatus());
				context.startActivity(cancelIntent);
				break;
			case R.id.btn_order_mark:
				markIntent.putExtra(MarkActivity.TAG_MARK_ORDER_FROM, MarkActivity.ORDER_FROM_MOVING);
				markIntent.putExtra(MarkActivity.TAG_MARK_ORDER_ID, orderList.get(position).getBjOrderId());
			    context.startActivity(markIntent);
				break;
			case R.id.btn_order_modify_confirm:
				context.sendBroadcast(new Intent(TCBroadcastAction.DIALOG_SHOW));
				confirmOrderModify(orderList.get(position).getBjOrderId());
				break;
			case R.id.btn_order_moving_part_pay:
				context.sendBroadcast(new Intent(TCBroadcastAction.DIALOG_SHOW));
				payMoney(orderList.get(position).getBjOrderId(),1);
				break;
			case R.id.btn_order_moving_finish:
				context.sendBroadcast(new Intent(TCBroadcastAction.DIALOG_SHOW));
				confirmOrderFinish(orderList.get(position).getBjOrderId());
				break;
			default:
				break;
			}
		}
	}
	
/**
 * 
* @Description: 掉起微信支付
* @param orderId
* djFlag 是否是支付定金，1为是，0和空为不是
* @return void
* @throws
* @autour wzq
* @date 2015-9-14 下午7:10:25
* @update (date)
 */
	private void payMoney(String orderId,int djFlag) {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
        params= HttpParamUtil.getMovingWxPay(context, orderId, djFlag);
        KJLoger.debug(params.getUrlParams().toString());
        kjh.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_ORDER_WXPAY, params, new HttpCallBack() {

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				String str;
				try {
					str = URLDecoder.decode(new String(t), "UTF-8");
					KJLoger.debug(str);
					WebData webData = TcJsParser.getWedataData(str);
					if (webData.getStatus() == 1) {
						WxPay payParam =JSON.parseObject(webData.getData(), WxPay.class);
						initWxPay(payParam);
					} else {
						
					}
					
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			
			
			@Override
    		public void onFailure(int errorNo, String strMsg) {
    			super.onFailure(errorNo, strMsg);
    		}
    		
    		@Override
    		public void onFinish() {
    			super.onFinish();
    		}
        });
	}
	
	/**
	 * 
	* @Description: 获取验证密钥
	* @param params
	* @return
	* @return String
	* @throws
	* @autour wzq
	* @date 2015-9-14 上午8:23:03
	* @update (date)
	 */
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);
		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",appSign);
		return appSign;
	}
	
	private void initWxPay(WxPay payParam) {
		req.appId = Constants.APP_ID;
		req.partnerId = Constants.MCH_ID;
		req.prepayId = payParam.getPrepayid();
		req.packageValue = "Sign=WXPay";
		req.nonceStr = payParam.getRad();
		req.timeStamp =System.currentTimeMillis()/1000+"";
		
		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
//		req.sign = payParam.getSign();
		req.sign = genAppSign(signParams);
		msgApi.registerApp(Constants.APP_ID);
		msgApi.sendReq(req);
	}
	
	
	/**
	 * 
	* @Description: TODO
	* @param priceTv 价格显示
	* @param orderStateTv 状态显示
	* @param payBtn   支付
	* @param cancelBtn 取消
	* @param markBtn 评价
	* @param caKanBtn 查看
	* @param confirmBtn 确定
	* @param orderInfo 
	          为1，待响应状态 （取消，定金支付）
		  为2，待收货状态 （取消，修改确定（未确定））
		  为3，待装货状态（取消，支付，修改确定（未确定））
		  为4，配送中（支付（全款）   完成 ）
		  为5，完成（评价）
	* @throws
	* @autour wzq
	* @date 2015-9-22 上午10:23:50
	* @update (date)
	 */
	private void refreashItemUiByStatus(TextView priceTv,TextView orderStateTv,Button payBtn,Button cancelBtn,Button markBtn,Button caKanBtn,Button confirmBtn,Button partPay,Button finishBtn, BjOrderInfo orderInfo) {
		
		switch (orderInfo.getStatus()) {
		case TcConfig.OrderStatus.PRE_RESPONSE://待响应状态 （取消，定金支付）
			orderStateTv.setText(TcConfig.OrderStatusLable.PRE_RES);
			orderStateTv.setTextColor(context.getResources().getColor(R.color.order_state_green));
			cancelBtn.setVisibility(View.VISIBLE);
			markBtn.setVisibility(View.GONE);
			caKanBtn.setVisibility(View.GONE);
		    priceTv.setVisibility(View.VISIBLE);
		    payBtn.setVisibility(View.GONE);
		    if(TcUtil.getMovingPay(orderInfo)==TcUtil.OrderPayState.PAY_NULL){
		    	if(TcUtil.getMovingPay(orderInfo)==TcUtil.OrderPayState.PAY_PART){
		    		payBtn.setVisibility(View.VISIBLE);
		    		if(orderInfo.getPayTypeId()!=1){
		    			partPay.setBackgroundResource(R.drawable.btn_disabled);
		    			partPay.setClickable(false);
					}
		    	}else{
		    		payBtn.setVisibility(View.VISIBLE);
		    		partPay.setVisibility(View.VISIBLE);
		    		if(orderInfo.getPayTypeId()!=1){
		    			partPay.setBackgroundResource(R.drawable.btn_disabled);
		    			partPay.setClickable(false);
		    			payBtn.setBackgroundResource(R.drawable.btn_disabled);
		    			payBtn.setClickable(false);
					}
		    	}
		    }
			break;
		case TcConfig.OrderStatus.PRE_TAKEGOODS://待收货状态 （取消，修改确定（未确定））
			orderStateTv.setText(TcConfig.OrderStatusLable.PRE_CARRAY);
			orderStateTv.setTextColor(context.getResources().getColor(R.color.order_state_green));
			partPay.setVisibility(View.GONE);
			markBtn.setVisibility(View.GONE);
			caKanBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.VISIBLE);
			priceTv.setVisibility(View.VISIBLE);
		    if(TcUtil.getMovingPay(orderInfo)==TcUtil.OrderPayState.PAY_NULL){
		    	if(TcUtil.getMovingPay(orderInfo)==TcUtil.OrderPayState.PAY_PART){
		    		payBtn.setVisibility(View.VISIBLE);
		    		if(orderInfo.getPayTypeId()!=1){
		    			payBtn.setBackgroundResource(R.drawable.btn_disabled);
		    			payBtn.setClickable(false);
					}
		    	}else{
		    		payBtn.setVisibility(View.VISIBLE);
		    		partPay.setVisibility(View.VISIBLE);
		    		if(orderInfo.getPayTypeId()!=1){
		    			partPay.setBackgroundResource(R.drawable.btn_disabled);
		    			partPay.setClickable(false);
		    			payBtn.setBackgroundResource(R.drawable.btn_disabled);
		    			payBtn.setClickable(false);
					}
		    	}
		    }
			break;
			
		case TcConfig.OrderStatus.PRE_CARRY://（取消，支付，修改确定（未确定））
			orderStateTv.setText(TcConfig.OrderStatusLable.PRE_CARRAY);
			orderStateTv.setTextColor(context.getResources().getColor(R.color.order_state_green));
			cancelBtn.setVisibility(View.GONE);
			partPay.setVisibility(View.GONE);
			markBtn.setVisibility(View.GONE);
			caKanBtn.setVisibility(View.GONE);
			priceTv.setVisibility(View.VISIBLE);
			
		    if(TcUtil.getMovingPay(orderInfo)==TcUtil.OrderPayState.PAY_NULL){
		    	if(TcUtil.getMovingPay(orderInfo)==TcUtil.OrderPayState.PAY_PART){
		    		payBtn.setVisibility(View.VISIBLE);
		    		if(orderInfo.getPayTypeId()!=1){
		    			payBtn.setBackgroundResource(R.drawable.btn_disabled);
		    			payBtn.setClickable(false);
					}
		    	}else{
		    		payBtn.setVisibility(View.VISIBLE);
		    		partPay.setVisibility(View.VISIBLE);
		    		if(orderInfo.getPayTypeId()!=1){
		    			payBtn.setBackgroundResource(R.drawable.btn_disabled);
		    			payBtn.setClickable(false);
		    			partPay.setBackgroundResource(R.drawable.btn_disabled);
		    			partPay.setClickable(false);
					}
		    	}
		    }
			
			break;
		case TcConfig.OrderStatus.DELIVERING://配送中（支付（全款）   完成 ）
			orderStateTv.setText(TcConfig.OrderStatusLable.CARRAY_ING);
			orderStateTv.setTextColor(context.getResources().getColor(R.color.order_state_green));
			caKanBtn.setVisibility(View.GONE);
			markBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
			partPay.setVisibility(View.GONE);
			finishBtn.setVisibility(View.VISIBLE);
			priceTv.setVisibility(View.VISIBLE);
			
			if (TcUtil.getMovingPay(orderInfo) != TcUtil.OrderPayState.PAY_ALL) {
				payBtn.setVisibility(View.VISIBLE);
				if(orderInfo.getPayTypeId()!=1){
					payBtn.setBackgroundResource(R.drawable.btn_disabled);
					payBtn.setClickable(false);
				}
			} else {
				payBtn.setVisibility(View.GONE);
			}
			
			break;
		case TcConfig.OrderStatus.FINISH:
			orderStateTv.setText(TcConfig.OrderStatusLable.FINISH);
			orderStateTv.setTextColor(context.getResources().getColor(R.color.order_state_blue));
			if(orderInfo.getIsCommentFlag()==0){
				markBtn.setVisibility(View.VISIBLE);
			}else{
				markBtn.setVisibility(View.GONE);
			}
			finishBtn.setVisibility(View.GONE);
			caKanBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
			priceTv.setVisibility(View.GONE);
			payBtn.setVisibility(View.GONE);
			partPay.setVisibility(View.GONE);
			break;
		case TcConfig.OrderStatus.CANCEL:
			orderStateTv.setText("已取消");
			orderStateTv.setTextColor(context.getResources().getColor(R.color.order_state_gray));
			priceTv.setVisibility(View.GONE);
			payBtn.setVisibility(View.GONE);
			markBtn.setVisibility(View.GONE);
			caKanBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
            partPay.setVisibility(View.GONE);
        	finishBtn.setVisibility(View.GONE);
			break;
		default:
			break;
		}
		
		caKanBtn.setVisibility(View.GONE);
		if(orderInfo.getIsUserConfirmFlag().equals("0")){
			confirmBtn.setVisibility(View.VISIBLE);
			payBtn.setVisibility(View.GONE);
		}else{
			confirmBtn.setVisibility(View.GONE);
		}
	}
	
	
	
	/**
	 * 
	* @Description: 订单确定修改
	* @param orderId
	* @return void
	* @autour wzq
	* @date 2015-9-21 下午4:32:52
	* @update (date)
	 */
	private void confirmOrderModify(String orderId) {

		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
        HttpParams params =new HttpParams();
        params=HttpParamUtil.getMovingOrderModify(context, orderId);
        kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_ORDER_CONFIRM, params, new HttpCallBack() {
			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
			}
			@Override
			public void onSuccess(String t) {
				try {
					String date=URLDecoder.decode(t, "UTF-8");
					KJLoger.debug(date);
					WebData webdata = TcJsParser.getWedataData(date); 
					if(webdata.getStatus()==1){
						context.sendBroadcast(new Intent(TCBroadcastAction.SUC_CONFIRM_MODIFY));
					}else{
						context.sendBroadcast(new Intent(TCBroadcastAction.ERROR_CONFIRM_MODIFY));
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				super.onSuccess(t);
			}
        });
	
	}
	
	
	/**
	 * 
	* @Description: 订单确定修改
	* @param orderId
	* @return void
	* @autour wzq
	* @date 2015-9-21 下午4:32:52
	* @update (date)
	 */
	private void confirmOrderFinish(String orderId) {

		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
        HttpParams params =new HttpParams();
        params=HttpParamUtil.getMovingOrderComplish(context, orderId);
        kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_ORDER_FINISH, params, new HttpCallBack() {
			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
			}
			@Override
			public void onSuccess(String t) {
				try {
					String date=URLDecoder.decode(t, "UTF-8");
					KJLoger.debug(date);
					WebData webdata = TcJsParser.getWedataData(date); 
					if(webdata.getStatus()==1){
						context.sendBroadcast(new Intent(TCBroadcastAction.SUC_MOVING_ORDER));
					}else{
						ViewInject.toast(context,webdata.getMsg());
						context.sendBroadcast(new Intent(TCBroadcastAction.ERROR_MOVING_ORDER));
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				super.onSuccess(t);
			}
        });
	
	}
	
	

}